package com.xingzhe.ucenter.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingzhe.ucenter.feignclient.CheckCodeClient;
import com.xingzhe.ucenter.mapper.XcUserMapper;
import com.xingzhe.ucenter.model.dto.AuthParamsDto;
import com.xingzhe.ucenter.model.dto.XcUserExt;
import com.xingzhe.ucenter.model.po.XcUser;
import com.xingzhe.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @description 账号密码认证
 * @author Mr.M
 * @date 2022/9/29 12:12
 * @version 1.0
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Resource
    XcUserMapper xcUserMapper;

    @Resource
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //先校验验证码  因为不先校验验证码可能会被恶心请求然后大量消耗数据库资源
        //输入的验证码
        String checkcode = authParamsDto.getCheckcode();
        //验证码对应的key
        String checkcodekey = authParamsDto.getCheckcodekey();
        if (StringUtils.isEmpty(checkcode)||StringUtils.isEmpty(checkcodekey)){
            throw  new RuntimeException("请输入验证码");
        }
        //远程调用验证码服务的接口去校验验证码
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (verify==null||!verify){
            throw new RuntimeException("验证码输入错误");
        }
        //拿到账号
        String username = authParamsDto.getUsername();
        //判断账号是否存在
        //去查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));

        //如果查询不到，则返回null，spring security框架会处理
        if (xcUser==null){
            throw new RuntimeException("账号不存在");
        }
        //有这个账号
        //则去查询密码
        String passwordDb = xcUser.getPassword();

        String passwordForm = authParamsDto.getPassword();
        //用户输入的密码和数据库的保存的密码比较
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches){
            throw new RuntimeException("账号或者密码错误");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        return xcUserExt;
    }
}
